<template>
  <div class="question-editor-page">
    <div class="question-editor-container">
      <!-- 题目基本信息 -->
      <div class="question-info-section">
        <div class="info-item">
          <span class="info-label">题目标题：</span>
          <el-input
            v-model="questionTitle"
            placeholder="请输入题目标题"
            clearable
            style="width: 100%"
          ></el-input>
        </div>

        <div class="info-row">
          <div class="info-item">
            <span class="info-label">题目分类：</span>
            <InputAndSearchWithTree
              v-model="questionCategory"
              placeholder="请选择题目分类"
              style="width: 100%"
            />
          </div>

          <div class="info-item">
            <span class="info-label">知识点：</span>
            <InputAndSearchWithList
              v-model="questionPoint"
              :category-id="questionCategory"
              placeholder="请选择知识点"
              style="width: 100%"
            />
          </div>

          <div class="info-item">
            <span class="info-label">题目难度：</span>
            <el-rate
              v-model="questionDifficulty"
              :max="5"
              :colors="difficultyColors"
              :void-color="'#EFF2F7'"
              :disabled-void-color="'#EFF2F7'"
              show-text
              :texts="difficultyTexts"
              class="difficulty-rate"
            />
          </div>
        </div>
      </div>

      <!-- 题型选择 -->
      <div class="question-type-selector">
        <el-radio-group v-model="questionType" @change="handleTypeChange">
          <el-radio-button label="single">单选题</el-radio-button>
          <el-radio-button label="multiple">多选题</el-radio-button>
          <el-radio-button label="judge">判断题</el-radio-button>
          <el-radio-button label="fill">填空题</el-radio-button>
          <el-radio-button label="essay">问答题</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 题目题干编辑器 -->
      <div class="editor-section">
        <div class="section-title">题目题干</div>
        <div style="border: 1px solid #dcdfe6; border-radius: 4px">
          <Toolbar
            style="border-bottom: 1px solid #dcdfe6"
            :editor="stemEditor"
            :defaultConfig="toolbarConfig"
            mode="default"
          />
          <Editor
            style="height: 200px; overflow-y: hidden"
            v-model="questionStem"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleStemEditorCreated"
            @onChange="handleStemChange"
          />
        </div>
      </div>

      <!-- 题目选项编辑器 -->
      <div class="editor-section" v-if="showOptions">
        <div class="section-title">题目选项</div>
        <div class="option-list">
          <div v-for="(option, index) in options" :key="'option-'+option.id" class="option-item">
            <div class="option-header">
              <span class="option-label">
                {{ getOptionLabel(index) }}
              </span>
              <el-button
                v-if="questionType !== 'judge'"
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="removeOption(index)"
              ></el-button>
            </div>
            <div v-if="questionType === 'judge'" v-html="option.content" class="static-option"></div>
            <div v-else style="border: 1px solid #dcdfe6; border-radius: 4px; margin-top: 5px">
              <Toolbar
                style="border-bottom: 1px solid #dcdfe6"
                :editor="optionEditors[index]"
                :defaultConfig="toolbarConfig"
                mode="default"
              />
              <Editor
                style="height: 150px; overflow-y: hidden"
                v-model="option.content"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="(editor) => handleOptionEditorCreated(editor, index)"
                @onChange="(editor) => handleOptionChange(editor, index)"
              />
            </div>
          </div>
        </div>
        <el-button
          v-if="questionType !== 'judge'"
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="addOption"
          style="margin-top: 10px"
        >
          添加选项
        </el-button>
      </div>

      <!-- 答案部分 -->
      <div class="editor-section">
        <div class="section-title">题目答案</div>
        <div v-if="questionType === 'single' || questionType === 'judge'">
          <el-radio-group v-model="answer">
            <el-radio
              v-for="(option, index) in options"
              :key="'radio-'+option.id"
              :label="option.value"
              :disabled="options.length === 0"
            >
              {{ questionType === 'judge' ? option.content : getOptionLabel(index) }}
            </el-radio>
          </el-radio-group>
        </div>

        <div v-else-if="questionType === 'multiple'">
          <el-checkbox-group
            v-model="answer"
            @change="handleCheckboxChange"
            class="horizontal-checkbox-group">
            <el-checkbox
              v-for="(option, index) in options"
              :key="'checkbox-'+option.id"
              :label="option.value"
              :value="option.value">
              {{ getOptionLabel(index) }}
            </el-checkbox>
          </el-checkbox-group>
        </div>

        <!-- 填空题答案编辑器（修改后） -->
        <div v-else-if="questionType === 'fill'">
          <div class="fill-answer-editor">
            <div style="border: 1px solid #dcdfe6; border-radius: 4px">
              <Toolbar
                style="border-bottom: 1px solid #dcdfe6"
                :editor="fillAnswerEditor"
                :defaultConfig="fillToolbarConfig"
                mode="default"
              />
              <Editor
                style="height: 200px; overflow-y: auto"
                v-model="fillAnswerHtml"
                :defaultConfig="fillEditorConfig"
                mode="default"
                @onCreated="handleFillAnswerEditorCreated"
                @onChange="handleFillAnswerChange"
              />
            </div>

            <!-- 答案分割预览 -->
            <div class="answer-preview" :class="{ error: hasSplitError }">
              <div v-for="(segment, index) in parsedAnswerSegments" :key="index" class="segment">
                <span class="segment-index">答案 {{ index + 1 }}：</span>
                <div class="segment-content editor-content-view" v-html="segment"></div>
              </div>
              <div v-if="parsedAnswerSegments.length === 0" class="empty-tip">
                未检测到有效答案（请使用分号 ; 或 ；分隔）
              </div>
            </div>
          </div>
        </div>

        <div v-else-if="questionType === 'essay'">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px">
            <Toolbar
              style="border-bottom: 1px solid #dcdfe6"
              :editor="answerEditor"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 200px; overflow-y: hidden"
              v-model="answer"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleAnswerEditorCreated"
              @onChange="handleAnswerChange"
            />
          </div>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="footer-actions">
        <el-button type="primary" @click="submitQuestion">提交题目</el-button>
        <el-button @click="resetForm">重置</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import { Boot } from '@wangeditor/editor'
import formulaModule from '@wangeditor/plugin-formula'
import { getToken } from '@/utils/auth'
import { getTempToken } from '@/api/files/file'
import { addQuestions } from "@/api/question/manage"
import InputAndSearchWithTree from '@/components/InputAndSearchWithTree'
import InputAndSearchWithList from '@/components/InputAndSearchWithList'

// 导入公式插件
import kityformula from "@/utils/formula/kityformula"
import myscriptMath from "@/utils/formula/myscriptMath"

export default {
  name: 'QuestionEditorPage',
  components: { Editor, Toolbar, InputAndSearchWithTree, InputAndSearchWithList },
  data() {
    return {
      // 填空题专用数据
      fillAnswerHtml: '',
      fillAnswerEditor: null,
      parsedAnswerSegments: [],
      hasSplitError: false,

      // 填空题编辑器配置
      fillToolbarConfig: {
        excludeKeys: ['group-video', 'insertImage'],
        insertKeys: {
          index: 0,
          keys: ['insertFormula', 'myscriptMath']
        }
      },
      fillEditorConfig: {
        placeholder: '请输入答案，用分号 ; 或 ；分隔多个答案...',
        MENU_CONF: {
          uploadImage: false, // 填空题不需要图片
          insertFormula: {
            transformFormula: (latex) => {
              // 自动转义公式中的分号
              return latex.replace(/[;；]/g, '\\semicolon')
            }
          }
        }
      },

      difficultyColors: ['#FFD700', '#FFA500', '#FF8C00', '#FF4500', '#FF0000'],
      difficultyTexts: ['简单', '较易', '中等', '较难', '困难'],
      questionTitle: '',
      questionCategory: '',
      questionPoint: '',
      questionDifficulty: 1,
      questionType: 'single',
      questionStem: '',
      options: [],
      answer: null,
      stemEditor: null,
      answerEditor: null,
      optionEditors: [],
      toolbarConfig: {
        excludeKeys: ['group-video'],
        insertKeys: {
          index: 0,
          keys: ['insertFormula', 'kityFormula', 'editFormula', 'myscriptMath']
        }
      },
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            server: process.env.VUE_APP_BASE_API + '/file/upload/editor/imgs',
            fieldName: 'files',
            maxFileSize: 10 * 1024 * 1024,
            maxNumberOfFiles: 10,
            allowedFileTypes: ['image/*'],
            meta: {
              type: 'img'
            },
            headers: {
              Authorization: getToken()
            },
            customInsert(result, insertFn) {
              result.data.forEach(item => {
                insertFn(item.fileId, item.fileId, '')
              })
            }
          },
          insertImage: {
            onInsertedImage(imageNode) {
              if (imageNode == null) return
            },
            checkImage: () => true,
            parseImageSrc: async src => {
              const res = await getTempToken(src)
              return res.data[0].fileUrl
            }
          },
          fontSize: {
            fontSizeList: ['12px', '14px', '16px', '18px', '24px', '32px', '48px']
          },
          lineHeight: {
            lineHeightList: ['1', '1.5', '1.75', '2', '2.5', '3', '4']
          },
          hoverbarKeys: {
            formula: {
              menuKeys: ['editFormula']
            }
          }
        }
      }
    }
  },
  computed: {
    showOptions() {
      return ['single', 'multiple', 'judge'].includes(this.questionType)
    }
  },
  watch: {
    questionType(newType) {
      this.initOptions(newType)
    }
  },
  created() {
    // 注册公式插件
    Boot.registerModule(formulaModule)
    Boot.registerMenu(kityformula)
    Boot.registerMenu(myscriptMath)
    this.initOptions()
  },
  beforeDestroy() {
    this.destroyEditors()
  },
  methods: {

    renderFormulas() {
      this.$nextTick(() => {
        const formulas = document.querySelectorAll('.answer-preview [data-w-e-type="formula"]')
        formulas.forEach(element => {
          const latex = element.dataset.value
          const isInline = element.dataset.wEIsInline === 'true'

          try {
            const html = katex.renderToString(latex, {
              throwOnError: false,
              displayMode: !isInline,
              output: 'mathml'
            })

            // 创建新的容器
            const container = document.createElement(isInline ? 'span' : 'div')
            container.innerHTML = html

            // 添加自定义样式类
            if (!isInline) {
              const wrapper = document.createElement('div')
              wrapper.className = 'formula-container'
              wrapper.appendChild(container)
              element.parentNode.replaceChild(wrapper, element)
            } else {
              element.parentNode.replaceChild(container, element)
            }

          } catch (e) {
            console.error('Katex render error:', e)
            element.outerHTML = `<span style="color: red">公式错误: ${latex}</span>`
          }
        })
      })
    },


    // 初始化填空题编辑器
    handleFillAnswerEditorCreated(editor) {
      this.fillAnswerEditor = editor
      // 初始化内容
      if (this.answer) {
        if (typeof this.answer === 'string' && this.answer.includes('|')) {
          // 兼容旧数据（|分隔）
          this.fillAnswerHtml = this.answer.replace(/\|/g, '；')
        } else if (this.answer.html) {
          // 新数据（富文本格式）
          this.fillAnswerHtml = this.answer.html
        }
        this.updateAnswerSegments()
      }
    },

    // 实时解析答案
    handleFillAnswerChange() {
      this.updateAnswerSegments()
    },

    // 核心解析方法
    updateAnswerSegments() {
      const html = this.fillAnswerHtml
      this.parsedAnswerSegments = this.splitAnswerSegments(html)
      this.renderFormulas()
    },
    splitAnswerSegments(html) {
      // 1. 创建临时DOM
      const tempDiv = document.createElement('div')
      tempDiv.innerHTML = html

      // 2. 保护公式节点
      const formulaMarkers = []
      tempDiv.querySelectorAll('[data-w-e-type="formula"]').forEach((formula, i) => {
        const marker = `__FORMULA_${i}__`
        formulaMarkers.push(formula.outerHTML)
        formula.replaceWith(document.createTextNode(marker))
      })

      // 3. 分割文本（兼容中英文分号）
      const rawSegments = tempDiv.textContent.split(/[;；]/).map(s => s.trim())

      // 4. 恢复公式并生成结果
      return rawSegments
        .filter(text => text.length > 0)
        .map(text => {
          // 恢复公式标记
          let segmentHtml = text.replace(/__FORMULA_(\d+)__/g, (_, index) => {
            return formulaMarkers[parseInt(index)] || ''
          })

          // 自动包裹段落标签（如果不存在）
          if (!segmentHtml.startsWith('<')) {
            segmentHtml = `<p>${segmentHtml}</p>`
          }

          return segmentHtml
        })
    },
    generateUniqueId() {
      return Date.now() + Math.random().toString(36).substr(2, 5)
    },

    // 编辑器生命周期
    handleStemEditorCreated(editor) {
      this.stemEditor = editor
    },
    handleAnswerEditorCreated(editor) {
      this.answerEditor = editor
    },
    handleOptionEditorCreated(editor, index) {
      this.$set(this.optionEditors, index, editor)
    },
    handleStemChange(editor) {
      // 可以在这里处理题干变化
    },
    handleAnswerChange(editor) {
      // 可以在这里处理答案变化
    },
    handleOptionChange(editor, index) {
      // 可以在这里处理选项变化
    },
// 修改 destroyEditors 方法
    destroyEditors() {
      [this.stemEditor, this.answerEditor, this.fillAnswerEditor].forEach(editor => {
        if (editor) {
          editor.destroy()
        }
      })
      this.optionEditors.forEach(editor => {
        if (editor) {
          editor.destroy()
        }
      })
    },

    // 选项操作
    getOptionLabel(index) {
      return String.fromCharCode(65 + index)
    },
    addOption() {
      const newValue = String.fromCharCode(65 + this.options.length)
      this.options.push({
        id: this.generateUniqueId(),
        content: '',
        value: newValue
      })
    },
    removeOption(index) {
      const removedValue = this.options[index].value
      this.options.splice(index, 1)

      // 更新多选题答案
      if (this.questionType === 'multiple') {
        this.answer = this.answer.filter(v => v !== removedValue)
      } else if (['single', 'judge'].includes(this.questionType)) {
        if (this.answer === removedValue) {
          this.answer = this.options[0]?.value || ''
        }
      }

      // 重新生成选项值以确保连续性
      this.options.forEach((option, idx) => {
        option.value = String.fromCharCode(65 + idx)
      })
    },

    // 题型切换
    initOptions(type = this.questionType) {
      if (type === 'judge') {
        this.options = [
          { content: '正确', value: 'A', id: this.generateUniqueId() },
          { content: '错误', value: 'B', id: this.generateUniqueId() }
        ]
        this.answer = 'A'
      } else if (type === 'multiple') {
        this.options = [
          { content: '', value: 'A', id: this.generateUniqueId() },
          { content: '', value: 'B', id: this.generateUniqueId() }
        ]
        this.answer = []
      } else if (['single'].includes(type)) {
        this.options = [
          { content: '', value: 'A', id: this.generateUniqueId() },
          { content: '', value: 'B', id: this.generateUniqueId() }
        ]
        this.answer = ''
      } else {
        this.options = []
        this.answer = type === 'fill' ? '' : ''
      }
    },
    handleTypeChange(type) {
      this.questionType = type
      this.initOptions(type)
    },
    handleCheckboxChange(val) {
      // 确保answer始终是数组
      this.answer = Array.isArray(val) ? val : [val]
    },

    // 数据准备与提交
    async submitQuestion() {
      console.log('提交数据检查:', {
        answer: this.answer,
        fillAnswerHtml: this.fillAnswerHtml,
        parsedAnswerSegments: this.parsedAnswerSegments
      })

      try {
        if (!this.validateForm()) return

        const submitData = this.prepareSubmitData()
        console.log('最终提交数据:', submitData)

        const res = await addQuestions(submitData)
        res.code === 200 ? this.handleSuccess() : this.$message.error(res.msg)
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('提交题目失败')
      }
    },
    validateForm() {
      // 基础验证
      if (!this.questionTitle.trim()) {
        this.$message.warning('请输入题目标题')
        return false
      }
      if (!this.questionCategory) {
        this.$message.warning('请选择题目分类')
        return false
      }
      if (!this.questionStem.trim()) {
        this.$message.warning('请输入题目内容')
        return false
      }
      if (this.showOptions && this.options.length < 2) {
        this.$message.warning('至少需要2个选项')
        return false
      }

      // 答案验证
      if (this.questionType === 'fill') {
        if (!this.fillAnswerHtml || this.parsedAnswerSegments.length === 0) {
          this.$message.warning('请设置填空题答案')
          return false
        }
      } else {
        if (!this.answer || (Array.isArray(this.answer) && this.answer.length === 0)) {
          this.$message.warning('请设置题目答案')
          return false
        }
      }

      return true
    },
    prepareSubmitData() {
      const baseData = {
        questionTitle: this.questionTitle,
        questionText: this.questionStem,
        questionTextPlain: this.stemEditor?.getText().trim() || '',
        questionType: this.questionType,
        difficulty: String(this.questionDifficulty),
        categoryId: this.questionCategory,
        pointId: this.questionPoint,
        options: {
          type: this.questionType,
          items: this.options.map(opt => ({
            label: opt.value,
            value: opt.value,
            content: opt.content
          }))
        }
      }

      // 根据题型处理答案
      if (this.questionType === 'fill') {
        return {
          ...baseData,
          correctAnswer: this.processAnswer(),
          correctAnswerPlain: this.parsedAnswerSegments
            .map(seg => {
              const div = document.createElement('div')
              div.innerHTML = seg
              return div.textContent.trim()
            })
            .join('；')
        }
      } else {
        return {
          ...baseData,
          correctAnswer: this.answer,
          correctAnswerPlain: this.getPlainAnswer()
        }
      }
    },
    // 提交前的答案处理
    processAnswer() {
      if (this.questionType !== 'fill') return this.answer

      return {
        type: 'rich_text',
        html: this.fillAnswerHtml,
        segments: this.parsedAnswerSegments,
        plain: this.parsedAnswerSegments.map(seg => {
          const div = document.createElement('div')
          div.innerHTML = seg
          return div.textContent.trim()
        })
      }
    },
    // 填空题专用验证
    validateFillAnswers() {
      if (this.parsedAnswerSegments.length === 0) {
        this.$message.warning('请至少输入一个有效答案，并用分号分隔')
        return false
      }

      if (this.hasSplitError) {
        this.$message.error('公式中包含分号，请使用\\semicolon或点击工具栏公式按钮编辑')
        return false
      }

      return true
    },
    getPlainAnswer() {
      if (['single', 'judge'].includes(this.questionType)) {
        const option = this.options.find(opt => opt.value === this.answer)
        return `${this.answer}: ${option?.content || ''}`
      }
      if (this.questionType === 'multiple') {
        return this.answer.map(ans => {
          const option = this.options.find(opt => opt.value === ans)
          return `${ans}: ${option?.content || ''}`
        }).join('; ')
      }
      if (this.questionType === 'fill') {
        return this.fillAnswerEditor?.getText().trim().split('、').map(s => s.trim()).join('; ')
      }
      return this.answerEditor?.getText().trim()
    },

    // 重置表单
    resetForm() {
      // 保存需要保留的编辑器配置
      const { fillToolbarConfig, fillEditorConfig } = this

      // 重置整个data
      Object.assign(this.$data, this.$options.data.call(this))

      // 恢复编辑器配置
      this.fillToolbarConfig = fillToolbarConfig
      this.fillEditorConfig = fillEditorConfig

      // 重新初始化
      this.destroyEditors()
      this.initOptions()
    },
    handleSuccess() {
      this.$message.success('题目提交成功')
      this.resetForm()
    },

    // 图片处理相关方法
    async setContent(html, editorType = 'stem') {
      // 处理html
      try {
        // 1. 提取所有img的alt属性值
        const imgAlts = this.extractImgAlts(html);

        // 2. 获取临时token和文件信息
        const res = await getTempToken(imgAlts.join(','));
        if (res.code !== 200) {
          throw new Error('获取临时token失败: ' + (res.msg || ''));
        }

        // 3. 替换HTML中的图片URL
        const updatedHtml = this.replaceImgUrls(html, res.data);

        // 4. 设置编辑器内容
        if (editorType === 'stem' && this.stemEditor) {
          this.stemEditor.setHtml(updatedHtml)
          this.questionStem = updatedHtml
        } else if (editorType === 'answer' && this.answerEditor) {
          this.answerEditor.setHtml(updatedHtml)
          this.answer = updatedHtml
        }
      } catch (error) {
        console.error('处理图片URL失败:', error);
        if (editorType === 'stem') {
          this.stemEditor.setHtml(html)
          this.questionStem = html
        } else if (editorType === 'answer') {
          this.answerEditor.setHtml(html)
          this.answer = html
        }
      }
    },

    // 提取img的alt属性值
    extractImgAlts(html) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      const imgs = doc.querySelectorAll('img');
      return Array.from(imgs).map(img => img.getAttribute('alt') || '');
    },

    // 替换图片的URL
    replaceImgUrls(html, fileInfoList) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      const imgs = doc.querySelectorAll('img');

      // 创建alt到fileInfo的映射，方便查找
      const altToFileInfoMap = {};
      fileInfoList.forEach(fileInfo => {
        altToFileInfoMap[fileInfo.fileId] = fileInfo;
      });

      // 遍历所有图片元素
      imgs.forEach(img => {
        const alt = img.getAttribute('alt') || '';
        const fileInfo = altToFileInfoMap[alt];

        if (fileInfo && fileInfo.fileUrl) {
          // 替换src属性为新的URL
          img.setAttribute('src', fileInfo.fileUrl);

          // 如果需要保留其他属性，可以在这里处理
          // 例如保留style属性等
        }
      });

      // 将修改后的DOM转换回HTML字符串
      const serializer = new XMLSerializer();
      let updatedHtml = serializer.serializeToString(doc.body);

      // 移除自动添加的<body>标签（如果有）
      updatedHtml = updatedHtml.replace(/^<body>|<\/body>$/g, '');
      console.log('updatedHtml:', updatedHtml)

      return updatedHtml;
    }
  }
}
</script>

<style scoped lang="scss">

.fill-answer-editor {
  margin-top: 15px;
}

.answer-preview {
  margin-top: 15px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fafafa;

  &.error {
    border-color: #f56c6c;
    background: #fff6f6;
  }
}

.segment {
  margin-bottom: 8px;
  padding: 8px;
  background: white;
  border-radius: 3px;
  border-left: 3px solid #409EFF;

  &:last-child {
    margin-bottom: 0;
  }
}


.segment-index {
  font-weight: bold;
  color: #67c23a;
  margin-right: 10px;
}

.segment-content {
  display: inline-block;

  ::v-deep {
    p {
      margin: 0;
      display: inline;
    }

    [data-w-e-type="formula"] {
      background: #f0f7ff;
      padding: 0 2px;
      border-radius: 2px;
    }
  }
}

.empty-tip {
  color: #909399;
  font-size: 13px;
  text-align: center;
  padding: 10px;
}

// 添加公式容器样式
.formula-container {
  margin: 0.5em 0;
  padding: 0.5em;
  background: #f8f9fa;
  border-radius: 4px;
  display: inline-block;
  vertical-align: middle;
}

// 确保编辑器内容视图样式
.editor-content-view {
  display: inline;
  line-height: 1.8;

  p {
    margin: 0;
    display: inline;
  }
}

/* 上面是填空题样式 */

.question-editor-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;

  .question-editor-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
}

.question-info-section {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;

  .info-row {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -10px;

    .info-item {
      flex: 1;
      min-width: 250px;
      padding: 0 10px;
      margin-bottom: 15px;
    }
  }

  .info-label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #333;
  }
}

.section-title {
  font-size: 16px;
  color: #333;
  margin: 15px 0;
  font-weight: 600;
}

.option-label {
  background: #409EFF;
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
}

.option-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.option-item {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 10px;
  transition: all 0.3s;

  &:hover {
    background: #e9f5ff;
  }
}

.editor-section {
  margin-bottom: 25px;
}

.static-option {
  padding: 8px;
  margin-top: 5px;
  background: #fff;
  border-radius: 4px;
}

.question-type-selector {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
  border-top: 1px solid #eee;
  margin-top: 20px;
}

.option-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.horizontal-checkbox-group {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  align-items: center;

  .el-checkbox {
    margin: 0;
    padding: 0 15px 0 5px;
    height: 32px;
    display: flex;
    align-items: center;
    background: #f5f7fa;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      background: #e6f1ff;
    }

    &:deep(.el-checkbox__input) {
      margin-right: 5px;
    }

    &:deep(.el-checkbox__label) {
      padding-left: 5px;
      white-space: nowrap;
    }
  }
}
/** 难度星级样式 */
.difficulty-rate {
  :deep(.el-rate__item) {
    .el-rate__icon {
      transition: all 0.3s;

      &:hover {
        transform: scale(1.2);
      }
    }
  }

  :deep(.el-rate__text) {
    margin-left: 10px;
    font-size: 14px;
    color: #666;
    font-weight: 500;
  }
}

</style>

<style>
.w-e-full-screen-container {
  z-index: 2000 !important;
}

/* 公式工具栏弹窗层级调整 */
.w-e-toolbar .w-e-drop-list {
  z-index: 9999 !important; /* 确保高于编辑器容器 */
}

/* 数学公式弹窗层级 */
.w-e-modal {
  z-index: 10000 !important; /* 模态框需要更高层级 */
  position: fixed !important; /* 固定定位防止被裁剪 */
}

/* kityformula 和 myscriptMath 弹窗 */
.w-e-dialog {
  z-index: 10001 !important;
  position: fixed !important;
}

/* 公式选择弹窗 */
.formula-module {
  z-index: 10002 !important;
  position: fixed !important;
}

/* 编辑器容器样式 */
.editor-container {
  position: relative; /* 保持相对定位 */
  overflow: visible !important; /* 必须允许溢出 */
}


</style>
